<template>
  <div>
    <n-card :bordered="false" title="无线参数" class="mt-4 proCard">
      <n-grid :cols="3">
        <n-gi :span="1">
          <n-form label-placement="left" label-width="120px" :model="rfFormValue">
            <n-form-item label="加密模式">
              <n-select
                v-model:value="rfFormValue.dataEncryptionMode"
                :options="dataEncryptionModeOptions"
              />
            </n-form-item>
            <n-form-item v-show="rfFormValue.dataEncryptionMode !== 0" label="加密密码">
              <n-input v-model:value="rfFormValue.dataEncryptionKey" />
            </n-form-item>
            <n-form-item label="Mesh ID">
              <n-input v-model:value="rfFormValue.meshName" />
            </n-form-item>
            <n-form-item label="工作模式">
              <n-select v-model:value="rfFormValue.freqMode" :options="freqModeOptions" />
            </n-form-item>
            <n-form-item label="信道带宽(MHz)">
              <n-select v-model:value="rfFormValue.span" :options="spanOptions" />
            </n-form-item>
            <n-form-item label="频率列表">
              <n-select v-model:value="rfFormValue.freqDefault" :options="freqListOptions" />
              <n-button color="#E0531f" @click="handleFreqListDialog">
                <template #icon>
                  <n-icon><FormOutlined /></n-icon>
                </template>
              </n-button>
            </n-form-item>
            <n-form-item label="禁用频率范围">
              <n-button style="width: 100%" color="#E0531f" @click="handleForbiddenFreqListDialog">
                <template #icon>
                  <n-icon><FormOutlined /></n-icon>
                </template>
                <span>修改</span>
              </n-button>
            </n-form-item>
            <n-form-item label="天线1发射功率">
              <n-select v-model:value="rfFormValue.pwAtten1" :options="powerAttenOptions" />
            </n-form-item>
            <n-form-item label="天线2发射功率">
              <n-select v-model:value="rfFormValue.pwAtten2" :options="powerAtten2Options" />
            </n-form-item>
            <n-form-item label="射频收发">
              <n-select v-model:value="rfFormValue.rfDisable" :options="rfDisableOptions" />
            </n-form-item>
            <n-form-item>
              <n-button style="margin-left: 120px" color="#E0531f" @click="handlerfSubmit"
                >提交</n-button
              >
            </n-form-item>
          </n-form>
        </n-gi>
        <n-gi :span="2">
          <div style="padding-left: 16px">
            <n-button @click="handleTimer">{{
              isOpenRealInfo ? '关闭实时信息' : '打开实时信息'
            }}</n-button>
            <n-data-table :max-height="580" :columns="realInfoColumns" :data="realInfoData" />
          </div>
        </n-gi>
      </n-grid>
    </n-card>
    <n-card :bordered="false" class="mt-4 proCard">
      <n-grid :cols="6">
        <n-gi :span="2">
          <n-card title="传输设置" :bordered="false">
            <n-form label-placement="left" label-width="120px" :model="transferFormValue">
              <n-form-item label="数据传输模式">
                <n-select
                  :options="dataTransferModeOptions"
                  v-model:value="transferFormValue.dataTransferMode"
                />
                <n-button color="#E0531f" @click="handleDataTransferMode">
                  <template #icon>
                    <n-icon><SaveOutlined /></n-icon>
                  </template>
                </n-button>
              </n-form-item>
              <n-form-item label="链路信噪比过滤门限">
                <n-input-number
                  v-model:value="transferFormValue.linkSnrThreshold"
                  :min="-10"
                  :max="30"
                />
                <n-button
                  color="#E0531f"
                  style="margin-right: 1px"
                  @click="handleGlobalLinkSnrThreshold"
                >
                  <template #icon>
                    <n-icon><SaveOutlined /></n-icon>
                  </template>
                  建议全网配置
                </n-button>
                <n-button color="#E0531f" @click="handleLinkSnrThreshold">
                  <template #icon>
                    <n-icon><SaveOutlined /></n-icon>
                  </template>
                  单独配置
                </n-button>
              </n-form-item>
              <n-form-item label="发送信号的最大传输格式">
                <n-input-number v-model:value="transferFormValue.maxMcformat" :min="0" :max="15" />
                <n-button color="#E0531f" @click="handleMaxMcformat">
                  <template #icon>
                    <n-icon><SaveOutlined /></n-icon>
                  </template>
                </n-button>
              </n-form-item>
              <n-form-item label="最低传输格式">
                <n-input-number v-model:value="transferFormValue.minTF" :min="0" :max="13" />
                <n-button color="#E0531f" @click="handleMinTF">
                  <template #icon>
                    <n-icon><SaveOutlined /></n-icon>
                  </template>
                </n-button>
              </n-form-item>
            </n-form>
          </n-card>
        </n-gi>
        <n-gi :offset="1" :span="3">
          <n-card title="组播地址" :bordered="false">
            <n-tabs type="line">
              <n-tab-pane name="ipMulticastIncomingWhitelist" tab="白名单"
                ><div style="display: flex; flex-direction: column">
                  <div
                    ><span
                      style="
                        display: flex;
                        justify-content: center;
                        width: 100%;
                        text-align: center;
                        margin-bottom: 5px;
                      "
                      >可进入本节点组播ip数据白名单列表</span
                    ></div
                  >
                  <n-data-table
                    :max-height="250"
                    :columns="multicastIncomingWhiteColumns"
                    :data="multicastIncomingWhiteTableData"
                  />
                  <n-input-group style="margin-top: 15px; width: 50%">
                    <n-input
                      v-model:value="addMulticastIncomingWhiteValue"
                      type="text"
                      placeholder="224.0.0.0~239.255.255.255"
                    />
                    <n-button color="#E0531f" @click="handleAddMulticastIncomingWhiteList"
                      ><template #icon>
                        <n-icon>
                          <FolderAddOutlined />
                        </n-icon> </template
                      >增加ip地址</n-button
                    >
                  </n-input-group>
                </div></n-tab-pane
              >
              <n-tab-pane name="ipMulticastIncomingBlacklist" tab="黑名单"
                ><div style="display: flex; flex-direction: column">
                  <div
                    ><span
                      style="
                        display: flex;
                        justify-content: center;
                        width: 100%;
                        text-align: center;
                        margin-bottom: 5px;
                      "
                      >不可进入本节点组播ip数据黑名单列表</span
                    ></div
                  >
                  <n-data-table
                    :max-height="250"
                    :columns="multicastIncomingBlackColumns"
                    :data="multicastIncomingBlackTableData"
                  />
                  <n-input-group style="margin-top: 15px; width: 50%">
                    <n-input
                      v-model:value="addMulticastIncomingBlackValue"
                      type="text"
                      placeholder="224.0.0.0~239.255.255.255"
                    />
                    <n-button color="#E0531f" @click="handleAddMulticastIncomingBlackList"
                      ><template #icon>
                        <n-icon>
                          <FolderAddOutlined />
                        </n-icon> </template
                      >增加ip地址</n-button
                    >
                  </n-input-group>
                </div></n-tab-pane
              >
            </n-tabs>
          </n-card>
        </n-gi>
      </n-grid>
      <n-grid :cols="6">
        <n-gi :span="3">
          <n-card title="广播过滤" :bordered="false">
            <n-tabs
              type="line"
              v-model:value="ipBroadcastFilterModeValue"
              @update:value="handleSwitchChange"
            >
              <n-tab-pane :name="0" tab="白名单"
                ><div style="display: flex; flex-direction: column"
                  ><div
                    ><span
                      style="
                        display: flex;
                        justify-content: center;
                        width: 100%;
                        text-align: center;
                        margin-bottom: 5px;
                      "
                      >广播ip数据(udp)白名单列表</span
                    ></div
                  >
                  <n-data-table
                    :max-height="250"
                    :columns="ipBroadcastWhitelistColumns"
                    :data="ipBroadcastWhiteTableData"
                  />
                  <n-input-group style="margin-top: 15px">
                    <n-input-group-label>端口</n-input-group-label>
                    <n-input-number
                      v-model:value="addIpBroadcastWhitePortValue"
                      placeholder="1~65535"
                      :min="1"
                      :max="65535"
                    />
                    <n-input-group-label>优先级（值越大，优先级越高）</n-input-group-label>
                    <n-input-number
                      v-model:value="addIpBroadcastWhitePriorityValue"
                      placeholder="0~1"
                      :min="0"
                      :max="1"
                    />
                    <n-button color="#E0531f" @click="handleAddIpBroadcastWhitelist"
                      ><template #icon>
                        <n-icon>
                          <FolderAddOutlined />
                        </n-icon> </template
                      >增加</n-button
                    >
                  </n-input-group></div
                ></n-tab-pane
              >
              <n-tab-pane :name="1" tab="黑名单(请谨慎使用)"
                ><div style="display: flex; flex-direction: column"
                  ><div
                    ><span
                      style="
                        display: flex;
                        justify-content: center;
                        width: 100%;
                        text-align: center;
                        margin-bottom: 5px;
                      "
                      >广播ip数据(udp)黑名单列表</span
                    ></div
                  ><n-data-table
                    :max-height="250"
                    :columns="ipBroadcastBlacklistColumns"
                    :data="ipBroadcastBlackTableData"
                  />
                  <n-input-group style="margin-top: 15px">
                    <n-input-group-label>端口</n-input-group-label>
                    <n-input-number
                      v-model:value="addIpBroadcastBlackPortValue"
                      placeholder="1~65535"
                      :min="1"
                      :max="65535"
                    /><n-button color="#E0531f" @click="handleAddIpBroadcastBlacklist"
                      ><template #icon>
                        <n-icon>
                          <FolderAddOutlined />
                        </n-icon> </template
                      >增加</n-button
                    >
                  </n-input-group></div
                ></n-tab-pane
              >
            </n-tabs>
          </n-card>
        </n-gi>
        <n-gi :span="3">
          <n-card title="组播过滤" :bordered="false">
            <n-tabs
              type="line"
              v-model:value="ipMulticastFilterModeValue"
              @update:value="handleMulticastFilterSwitchChange"
            >
              <n-tab-pane :name="0" tab="白名单"
                ><div style="display: flex; flex-direction: column"
                  ><div
                    ><span
                      style="
                        display: flex;
                        justify-content: center;
                        width: 100%;
                        text-align: center;
                        margin-bottom: 5px;
                      "
                      >组播ip数据白名单列表</span
                    ></div
                  >
                  <n-data-table
                    :columns="ipMulticastWhitelistColumns"
                    :data="ipMulticastWhiteTableData"
                    :max-height="250"
                  />
                  <n-form
                    style="width: 50%; margin-top: 24px"
                    label-placement="left"
                    label-width="130px"
                    :model="ipMulticastWhiteFormValue"
                    ref="ipMulticastWhiteFormRef"
                    :rules="ipMulticastWhiteFormRules"
                  >
                    <n-form-item label="ip地址" path="address">
                      <n-input
                        v-model:value="ipMulticastWhiteFormValue.address"
                        placeholder="224.0.0.0~239.255.255.255"
                      />
                    </n-form-item>
                    <n-form-item label="优先级(值越大，优先级越高)" path="priority">
                      <n-input-number
                        v-model:value="ipMulticastWhiteFormValue.priority"
                        placeholder="0~1"
                        :min="0"
                        :max="1"
                      />
                    </n-form-item>
                    <n-form-item label="数据速率kbps(不确定时写0)" path="dataRate">
                      <n-input-number v-model:value="ipMulticastWhiteFormValue.dataRate" :min="0" />
                    </n-form-item>
                    <n-form-item label="跳数(不确定时写0)" path="maxHopCount">
                      <n-input-number
                        v-model:value="ipMulticastWhiteFormValue.maxHopCount"
                        :min="0"
                      />
                    </n-form-item>
                    <n-form-item>
                      <n-button
                        color="#E0531f"
                        style="margin-left: 130px"
                        @click="handleIpMulticastWhiteSubmit"
                        ><template #icon>
                          <n-icon>
                            <FolderAddOutlined />
                          </n-icon> </template
                        >增加</n-button
                      >
                    </n-form-item>
                  </n-form></div
                ></n-tab-pane
              >
              <n-tab-pane :name="1" tab="黑名单(请谨慎使用)"
                ><div style="display: flex; flex-direction: column"
                  ><div
                    ><span
                      style="
                        display: flex;
                        justify-content: center;
                        width: 100%;
                        text-align: center;
                        margin-bottom: 5px;
                      "
                      >组播ip数据黑名单列表</span
                    ></div
                  >
                  <n-data-table
                    :columns="ipMulticastBlacklistColumns"
                    :data="ipMulticastBlackTableData"
                    :max-height="250"
                  />
                  <n-form
                    style="width: 50%; margin-top: 24px"
                    label-placement="left"
                    label-width="130px"
                    :model="ipMulticastBlackFormValue"
                    ref="ipMulticastBlackFormRef"
                    :rules="ipMulticastBlackFormRules"
                  >
                    <n-form-item label="ip地址" path="address">
                      <n-input
                        v-model:value="ipMulticastBlackFormValue.address"
                        placeholder="224.0.0.0~239.255.255.255"
                      />
                    </n-form-item>
                    <n-form-item>
                      <n-button
                        color="#E0531f"
                        style="margin-left: 130px"
                        @click="handleIpMulticastBlackSubmit"
                        ><template #icon>
                          <n-icon>
                            <FolderAddOutlined />
                          </n-icon> </template
                        >增加</n-button
                      >
                    </n-form-item>
                  </n-form></div
                ></n-tab-pane
              >
              <n-tab-pane :name="2" tab="IGMP智能(全网一致)"
                ><div style="padding: 48px 0">
                  <n-empty size="large" description="无数据,仅提供选择IGMP模式" /> </div
              ></n-tab-pane>
            </n-tabs>
          </n-card>
        </n-gi>
      </n-grid>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, h, onBeforeUnmount, onMounted, ref } from 'vue';
  import {
    dataEncryptionModeOptions,
    spanOptions,
    freqModeOptions,
    powerAttenOptions,
    powerAtten2Options,
    rfDisableOptions,
    dataTransferModeOptions,
  } from '.';
  import { getRfConfig } from '@/api/rfconfig/rfconfig';
  import { NButton, NDataTable, NIcon, NInput, NInputNumber, useMessage } from 'naive-ui';
  import { FormOutlined, PlusOutlined, SaveOutlined, FolderAddOutlined } from '@vicons/antd';
  import { useDialog, FormInst, FormRules, FormItemRule } from 'naive-ui';
  import { useDeviceInfo } from '@/store/modules/deviceInfo';
  import type { ForbiddenFreq } from '@/api/config';
  import { isHasOverlap, isMulticastIp } from '@/utils/is';
  import type { RfConfig, TransferConfig } from '@/api/rfconfig/rfconfig';
  import type {
    IpBroadcastWhitelistItem,
    IpBroadcastBlacklistItem,
    IpMulticastWhitelistItem,
    IpMulticastBlacklistItem,
  } from '@/api/config';
  import { updateRfConfig, updateTransferConfig } from '@/api/rfconfig/rfconfig';
  import {
    getStatusConfig,
    getStatusByIp,
    getRssiStatus,
    getRssiStatusByIp,
    getStatusAdvanced,
    getStatusAdvancedByIp,
  } from '@/api/status';
  import { useGlobalConfig } from '@/store/modules/globalConfig';

  const globalConfig = useGlobalConfig();

  const message = useMessage();
  const freqListDialog = useDialog();
  const ForbiddenFreqListDialog = useDialog();
  const dataTransferModeDialog = useDialog();

  const useDeviceInfoStore = useDeviceInfo();

  const rfFormValue = ref<RfConfig>({
    dataEncryptionMode: 0,
    dataEncryptionKey: '',
    meshName: '',
    freqMode: '',
    span: 0,
    freqDefault: 0,
    freqList: [],
    forbiddenFreqBands: [],
    pwAtten1: 0,
    pwAtten2: 0,
    rfDisable: 0,
  });

  const transferFormValue = ref<TransferConfig>({
    dataTransferMode: 0,
    linkSnrThreshold: 0,
    maxMcformat: 0,
    minTF: 0,
  });

  const freqListOptions = computed(() => {
    return rfFormValue.value.freqList.map((freq, index) => ({
      label: `${freq / 1000000} MHz`,
      value: index,
    }));
  });

  const freqListTableData = ref([...rfFormValue.value.freqList]);
  const addFreqListData = ref<number>(0);
  const addFreqListMinData = ref<number>(0);
  const addFreqListMaxData = ref<number>(0);
  const addFreqListInterval = ref<number>(0);

  const forbiddenFreqListTableData = ref<ForbiddenFreq[]>([
    ...rfFormValue.value.forbiddenFreqBands,
  ]);
  const addForbiddenFreqListMinData = ref<number>(0);
  const addForbiddenFreqListMaxData = ref<number>(0);

  const spnaMap = new Map<number, number>([
    [0, 2500000],
    [1, 5000000],
    [2, 10000000],
    [3, 20000000],
  ]);

  const freqListColumns = [
    {
      title: '频率值',
      key: 'freq',
      //width: 200, // 添加固定宽度
    },
    {
      title: '操作',
      key: 'actions',
      //width: 100,
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteFreq(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];

  const forbiddenFreqListColumns = [
    {
      title: '最小频率(MHz)',
      key: 'freqMin',
    },
    {
      title: '最大频率(MHz)',
      key: 'freqMax',
    },
    {
      title: '操作',
      key: 'action',
      render: (row: any, index: number) =>
        h(
          NButton,
          { size: 'small', type: 'error', onClick: () => handleDeleteForbiddenFreq(row, index) },
          { default: () => '删除' }
        ),
    },
  ];

  function handleDeleteFreq(row: any, index: number) {
    // 删除频率的逻辑
    // console.log(row, index);
    freqListTableData.value.splice(index, 1);
  }

  function handleDeleteForbiddenFreq(row: any, index: number) {
    forbiddenFreqListTableData.value.splice(index, 1);
  }

  function handleFreqListDialog() {
    freqListTableData.value = [...rfFormValue.value.freqList];
    freqListDialog.create({
      style: { width: '700px' },
      title: () => `频率列表 最大允许个数: 16 总数: ${freqListTableData.value.length}`,
      content: () =>
        h(
          'div',
          {
            style:
              'display: flex; flex-direction: column; padding: 20px; width: 100%; height: 100%',
          },
          [
            // 频率操作列表
            h(NDataTable, {
              columns: freqListColumns,
              data: freqListTableData.value.map((freq) => ({
                freq: `${freq / 1000000} MHz`,
              })),
              bordered: true,
              style: { width: '100%', marginBottom: '10px' }, // 添加表格宽度
              //scrollX: 'max-content', // 允许水平滚动
              maxHeight: 250,
            }),
            // 清空和排序
            h('div', { style: { marginBottom: '10px' } }, [
              h(
                NButton,
                {
                  size: 'small',
                  color: '#fad733',
                  style: { marginRight: '5px' },
                  onClick: () => {
                    freqListTableData.value = [];
                  },
                },
                { default: () => '清空' }
              ),
              h(
                NButton,
                {
                  size: 'small',
                  color: '#27c24c',
                  onClick: () => {
                    freqListTableData.value.sort((a, b) => a - b);
                  },
                },
                { default: () => '从小到大排序' }
              ),
            ]),
            h('div', { style: { marginBottom: '10px' } }, [
              h(
                'span',
                `可用频率范围: ${useDeviceInfoStore.getFreqMin / 1000000}~${
                  useDeviceInfoStore.getFreqMax / 1000000
                }`
              ),
              h(
                'span',
                { style: { marginLeft: '5px' } },
                `禁用频率范围: ${rfFormValue.value.forbiddenFreqBands
                  .map((obj) => `${obj.freqMin / 1000000}~${obj.freqMax / 1000000}`)
                  .join(' ')}`
              ),
            ]),
            h('div', { style: { display: 'flex', marginBottom: '10px' } }, [
              h(
                NInputNumber,
                {
                  min: useDeviceInfoStore.getFreqMin / 1000000,
                  max: useDeviceInfoStore.getFreqMax / 1000000,
                  value: addFreqListData.value === 0 ? null : addFreqListData.value,
                  onUpdateValue: (value: number) => {
                    //console.log(value);
                    addFreqListData.value = value;
                  },
                },
                {
                  suffix: () => 'MHz',
                }
              ),
              h(
                NButton,
                {
                  size: 'medium',
                  onClick: () => {
                    const freq = addFreqListData.value * 1000000;
                    if (
                      freq < useDeviceInfoStore.getFreqMin ||
                      freq > useDeviceInfoStore.getFreqMax
                    ) {
                      message.error('添加的频率不在频率范围内, 请重新检查!');
                      addFreqListData.value = 0;
                      return;
                    }
                    if (freqListTableData.value.includes(freq)) {
                      message.error('添加的频率已存在, 请重新添加!');
                      addFreqListData.value = 0;
                      return;
                    }
                    if (freqListTableData.value.length + 1 > 16) {
                      message.error('频率列表已达最大允许个数, 不能添加!');
                      addFreqListData.value = 0;
                      return;
                    }
                    freqListTableData.value.push(freq);
                    addFreqListData.value = 0;
                  },
                },
                {
                  default: () => '增加',
                  icon: () => h(NIcon, null, { default: () => h(PlusOutlined) }),
                }
              ),
            ]),
            h('div', { style: { display: 'flex' } }, [
              h(NInputNumber, {
                showButton: false,
                min: useDeviceInfoStore.getFreqMin / 1000000,
                max: useDeviceInfoStore.getFreqMax / 1000000,
                value: addFreqListMinData.value === 0 ? null : addFreqListMinData.value,
                onUpdateValue: (value: number) => {
                  addFreqListMinData.value = value;
                },
              }),
              h('span', '~'),
              h(NInputNumber, {
                showButton: false,
                min: useDeviceInfoStore.getFreqMin / 1000000,
                max: useDeviceInfoStore.getFreqMax / 1000000,
                style: { marginRight: '5px' },
                value: addFreqListMaxData.value === 0 ? null : addFreqListMaxData.value,
                onUpdateValue: (value: number) => {
                  addFreqListMaxData.value = value;
                },
              }),
              h(
                NInputNumber,
                {
                  showButton: false,
                  value: addFreqListInterval.value === 0 ? null : addFreqListInterval.value,
                  onUpdateValue: (value: number) => {
                    addFreqListInterval.value = value;
                  },
                },
                {
                  prefix: () => '间隔',
                  suffix: () => 'MHz',
                }
              ),
              h(
                NButton,
                {
                  color: '#7266ba',
                  onClick: () => {
                    const minFreq = addFreqListMinData.value * 1000000;
                    const maxFreq = addFreqListMaxData.value * 1000000;
                    const intervalFreq = addFreqListInterval.value * 1000000;
                    if (
                      minFreq < useDeviceInfoStore.getFreqMin ||
                      minFreq > useDeviceInfoStore.getFreqMax ||
                      maxFreq < useDeviceInfoStore.getFreqMin ||
                      maxFreq > useDeviceInfoStore.getFreqMax
                    ) {
                      message.error('批量输入频率最大最小值不在可用频率范围内, 请检查！');
                      addFreqListMaxData.value =
                        addFreqListMinData.value =
                        addFreqListInterval.value =
                          0;
                      return;
                    }
                    if (minFreq > maxFreq) {
                      message.error('最小值不能大于最大值, 请检查!');
                      addFreqListMaxData.value =
                        addFreqListMinData.value =
                        addFreqListInterval.value =
                          0;
                      return;
                    }
                    if (intervalFreq === 0) {
                      message.error('间隔不能为空!');
                      addFreqListMaxData.value =
                        addFreqListMinData.value =
                        addFreqListInterval.value =
                          0;
                      return;
                    }
                    let addFreqArr: number[] = [];
                    for (let freq = minFreq; freq <= maxFreq; freq += intervalFreq) {
                      if (freqListTableData.value.includes(freq)) {
                        message.error('批量添加的频率与频率列表频率存在交集, 请检查!');
                        addFreqListMaxData.value =
                          addFreqListMinData.value =
                          addFreqListInterval.value =
                            0;
                        return;
                      }
                      addFreqArr.push(freq);
                    }
                    if (freqListTableData.value.length + addFreqArr.length > 16) {
                      message.error('批量添加频率超过频率列表最大允许个数!');
                      addFreqListMaxData.value =
                        addFreqListMinData.value =
                        addFreqListInterval.value =
                          0;
                      return;
                    }
                    freqListTableData.value = [...freqListTableData.value, ...addFreqArr];
                    addFreqListMaxData.value =
                      addFreqListMinData.value =
                      addFreqListInterval.value =
                        0;
                  },
                },
                { default: () => '批量增加' }
              ),
            ]),
          ]
        ),
      positiveText: '修改',
      negativeText: '取消',
      onPositiveClick: () => {
        // console.log(freqListTableData.value);
        rfFormValue.value.freqList = [...freqListTableData.value];
        message.success('操作成功');
      },
      onNegativeClick: () => {
        message.info('已取消');
      },
    });
  }

  function handleForbiddenFreqListDialog() {
    forbiddenFreqListTableData.value = [...rfFormValue.value.forbiddenFreqBands];
    ForbiddenFreqListDialog.create({
      style: { width: '700px' },
      title: '禁用频率范围',
      content: () =>
        h('div', {}, [
          h(NDataTable, {
            columns: forbiddenFreqListColumns,
            data: forbiddenFreqListTableData.value.map((obj) => ({
              freqMin: `${obj.freqMin / 1000000}MHz`,
              freqMax: `${obj.freqMax / 1000000}MHz`,
            })),
            bordered: true,
            style: { width: '100%', marginBottom: '10px' }, // 添加表格宽度
            //scrollX: 'max-content', // 允许水平滚动
            maxHeight: 250,
          }),
          h('div', { style: { marginBottom: '10px' } }, [
            h(
              NButton,
              {
                size: 'small',
                color: '#fad733',
                onClick: () => {
                  forbiddenFreqListTableData.value = [];
                },
              },
              { default: () => '清空' }
            ),
          ]),
          h('div', {}, [
            h(
              'span',
              `可用频率范围: ${useDeviceInfoStore.getFreqMin / 1000000}~${
                useDeviceInfoStore.getFreqMax / 1000000
              }`
            ),
          ]),
          h('div', { style: { marginBottom: '10px' } }, [
            h(
              'span',
              `频率列表: ${rfFormValue.value.freqList.map((freq) => freq / 1000000).join(',')}`
            ),
          ]),
          h('div', {}, [
            h('span', '禁用频率范围'),
            h(
              NInputNumber,
              {
                style: { width: '50%', marginBottom: '10px' },
                value:
                  addForbiddenFreqListMinData.value === 0
                    ? null
                    : addForbiddenFreqListMinData.value,
                onUpdateValue: (value: number) => {
                  addForbiddenFreqListMinData.value = value;
                },
              },
              {
                prefix: () => '最小频率(MHz)',
                //suffix: () => 'MHz',
              }
            ),
            h(
              NInputNumber,
              {
                style: { width: '50%', marginBottom: '10px' },
                value:
                  addForbiddenFreqListMaxData.value === 0
                    ? null
                    : addForbiddenFreqListMaxData.value,
                onUpdateValue: (value: number) => {
                  addForbiddenFreqListMaxData.value = value;
                },
              },
              {
                prefix: () => '最大频率(MHz)',
                //suffix: () => 'MHz',
              }
            ),
            h(
              NButton,
              {
                color: '#7266ba',
                onClick: () => {
                  //console.log(addForbiddenFreqListMinData.value);
                  const minFreq = addForbiddenFreqListMinData.value * 1000000;
                  const maxFreq = addForbiddenFreqListMaxData.value * 1000000;
                  if (
                    minFreq < useDeviceInfoStore.getFreqMin ||
                    minFreq > useDeviceInfoStore.getFreqMax ||
                    maxFreq < useDeviceInfoStore.getFreqMin ||
                    maxFreq > useDeviceInfoStore.getFreqMax
                  ) {
                    message.error('最小频率或最大频率不在可用频率范围内，请检查!');
                    addForbiddenFreqListMinData.value = addForbiddenFreqListMaxData.value = 0;
                    return;
                  }

                  if (minFreq > maxFreq) {
                    message.error('最小频率不应大于最大频率，请检查!');
                    addForbiddenFreqListMinData.value = addForbiddenFreqListMaxData.value = 0;
                    return;
                  }

                  const span = spnaMap.get(rfFormValue.value.span);
                  if (span === undefined) {
                    message.error('无对应带宽');
                    return;
                  }
                  for (let i = 0; i < rfFormValue.value.freqList.length; ++i) {
                    const min = rfFormValue.value.freqList[i] - span / 2;
                    const max = rfFormValue.value.freqList[i] + span / 2;
                    if (isHasOverlap(minFreq, maxFreq, min, max)) {
                      message.error(
                        `禁用频率范围: ${addForbiddenFreqListMinData.value}~${
                          addForbiddenFreqListMaxData.value
                        } 频率列表: ${rfFormValue.value.freqList[i] / 1000000}(工作频率范围: ${
                          min / 1000000
                        }~${max / 1000000})有交集`
                      );
                      addForbiddenFreqListMinData.value = addForbiddenFreqListMaxData.value = 0;
                      return;
                    }
                  }
                  for (let i = 0; i < forbiddenFreqListTableData.value.length; ++i) {
                    if (
                      isHasOverlap(
                        minFreq,
                        maxFreq,
                        forbiddenFreqListTableData.value[i].freqMin,
                        forbiddenFreqListTableData.value[i].freqMax
                      )
                    ) {
                      message.error(
                        `禁用频率范围: ${forbiddenFreqListTableData.value[i].freqMin / 1000000}~${
                          forbiddenFreqListTableData.value[i].freqMax / 1000000
                        }有交集`
                      );
                      addForbiddenFreqListMinData.value = addForbiddenFreqListMaxData.value = 0;
                      return;
                    }
                  }

                  const obj: ForbiddenFreq = { freqMin: minFreq, freqMax: maxFreq };
                  forbiddenFreqListTableData.value.push(obj);
                  addForbiddenFreqListMinData.value = addForbiddenFreqListMaxData.value = 0;
                  return;
                },
              },
              { default: () => '增加' }
            ),
          ]),
        ]),
      positiveText: '修改',
      negativeText: '取消',
      onPositiveClick: () => {
        rfFormValue.value.forbiddenFreqBands = [...forbiddenFreqListTableData.value];
        message.success('操作成功');
      },
      onNegativeClick: () => {
        message.info('已取消');
      },
    });
  }

  async function handlerfSubmit() {
    // console.log(11);
    updateRfConfig({
      ...rfFormValue.value,
      ...(globalConfig.getConfigGlobal ? { configGlobal: globalConfig.getConfigGlobal } : {}),
    })
      .then((result) => {
        // console.log(result);
        if (result === 'OK') {
          message.success('射频参数设置成功！');
        } else {
          message.error('射频参数设置失败！');
        }
      })
      .catch((err) => {
        // console.log(err);
        message.error('射频参数设置失败！');
      });
  }

  /*************************************传输配置*****************************************/
  async function handleDataTransferMode() {
    dataTransferModeDialog.warning({
      title: '警告',
      content: '设备将被自动重启',
      positiveText: '确定',
      negativeText: '取消',
      draggable: true,
      onPositiveClick: () => {
        updateTransferConfig({
          dataTransferMode: transferFormValue.value.dataTransferMode,
          ...(globalConfig.getConfigGlobal ? { configGlobal: globalConfig.getConfigGlobal } : {}),
        })
          .then((result) => {
            if (result === 'OK') {
              message.success('数据传输模式设置成功！');
            } else {
              message.error('数据传输模式设置失败！');
            }
          })
          .catch((err) => {
            message.error('数据传输模式设置失败！');
          });
      },
      onNegativeClick: () => {
        message.error('取消');
      },
    });
  }

  async function handleLinkSnrThreshold() {
    updateTransferConfig({
      linkSnrThreshold: transferFormValue.value.linkSnrThreshold,
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('链路信噪比过滤门限设置成功！');
        } else {
          message.error('链路信噪比过滤门限设置失败！');
        }
      })
      .catch((err) => {
        message.error('链路信噪比过滤门限设置失败！');
      });
  }

  async function handleGlobalLinkSnrThreshold() {
    updateTransferConfig({
      configGlobal: true,
      linkSnrThreshold: transferFormValue.value.linkSnrThreshold,
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('链路信噪比过滤门限全局设置成功！');
        } else {
          message.error('链路信噪比过滤门限全局设置失败！');
        }
      })
      .catch((err) => {
        message.error('链路信噪比过滤门限全局设置失败！');
      });
  }

  async function handleMaxMcformat() {
    updateTransferConfig({
      maxMcformat: transferFormValue.value.maxMcformat,
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('发送信号的最大传输格式设置成功！');
        } else {
          message.error('发送信号的最大传输格式设置失败！');
        }
      })
      .catch((err) => {
        message.error('发送信号的最大传输格式设置失败！');
      });
  }

  async function handleMinTF() {
    updateTransferConfig({
      minTF: transferFormValue.value.minTF,
      ...(globalConfig.getConfigGlobal ? { configGlobal: globalConfig.getConfigGlobal } : {}),
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('最低传输格式设置成功！');
        } else {
          message.error('最低传输格式设置失败！');
        }
      })
      .catch((err) => {
        message.error('最低传输格式设置失败！');
      });
  }

  /**********************************组播地址*****************************************/
  const multicastIncomingWhiteColumns = [
    { title: 'ipAddr', key: 'ipAddr' },
    {
      title: '操作',
      key: 'actions',
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteMulticastIncomingWhiteList(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];
  const multicastIncomingBlackColumns = [
    { title: 'ipAddr', key: 'ipAddr' },
    {
      title: '操作',
      key: 'actions',
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteMulticastIncomingBlackList(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];

  const multicastIncomingWhiteList = ref<string[]>([]);
  const multicastIncomingBlackList = ref<string[]>([]);
  const multicastIncomingWhiteTableData = computed(() => {
    return multicastIncomingWhiteList.value.map((ipaddr) => ({ ipAddr: ipaddr }));
  });
  const multicastIncomingBlackTableData = computed(() => {
    return multicastIncomingBlackList.value.map((ipaddr) => ({ ipAddr: ipaddr }));
  });

  const addMulticastIncomingWhiteValue = ref<string>('');
  const addMulticastIncomingBlackValue = ref<string>('');

  async function handleAddMulticastIncomingWhiteList() {
    // console.log(addMulticastIncomingWhiteValue.value);
    if (!isMulticastIp(addMulticastIncomingWhiteValue.value)) {
      message.error('请输入合法的组播地址!');
      return;
    }
    if (multicastIncomingWhiteList.value.includes(addMulticastIncomingWhiteValue.value)) {
      message.error('组播地址已存在!');
      return;
    }
    multicastIncomingWhiteList.value.push(addMulticastIncomingWhiteValue.value);
    updateTransferConfig({
      ipMulticastIncomingBlacklist: [],
      ipMulticastIncomingWhitelist: [...multicastIncomingWhiteList.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('组播地址白名单添加成功！');
        } else {
          message.error('组播地址白名单添加失败！');
        }
      })
      .catch((err) => {
        message.error('组播地址白名单添加失败！');
      });
  }

  async function handleDeleteMulticastIncomingWhiteList(row: any, index: number) {
    multicastIncomingWhiteList.value.splice(index, 1);
    updateTransferConfig({
      ipMulticastIncomingBlacklist: [],
      ipMulticastIncomingWhitelist: [...multicastIncomingWhiteList.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('组播地址白名单删除成功！');
        } else {
          message.error('组播地址白名单删除失败！');
        }
      })
      .catch((err) => {
        message.error('组播地址白名单删除失败！');
      });
  }

  async function handleAddMulticastIncomingBlackList() {
    // console.log(addMulticastIncomingWhiteValue.value);
    if (!isMulticastIp(addMulticastIncomingBlackValue.value)) {
      message.error('请输入合法的组播地址!');
      return;
    }
    if (multicastIncomingBlackList.value.includes(addMulticastIncomingBlackValue.value)) {
      message.error('组播地址已存在!');
      return;
    }
    multicastIncomingBlackList.value.push(addMulticastIncomingBlackValue.value);
    updateTransferConfig({
      ipMulticastIncomingBlacklist: [...multicastIncomingBlackList.value],
      ipMulticastIncomingWhitelist: [],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('组播地址黑名单添加成功！');
        } else {
          message.error('组播地址黑名单添加失败！');
        }
      })
      .catch((err) => {
        message.error('组播地址黑名单添加失败！');
      });
  }

  async function handleDeleteMulticastIncomingBlackList(row: any, index: number) {
    multicastIncomingBlackList.value.splice(index, 1);
    updateTransferConfig({
      ipMulticastIncomingBlacklist: [...multicastIncomingBlackList.value],
      ipMulticastIncomingWhitelist: [],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('组播地址黑名单删除成功！');
        } else {
          message.error('组播地址黑名单删除失败！');
        }
      })
      .catch((err) => {
        message.error('组播地址黑名单删除失败！');
      });
  }
  /**********************************组播过滤*****************************************/
  const ipMulticastFilterModeValue = ref<number>(0);

  const ipMulticastWhitelist = ref<IpMulticastWhitelistItem[]>();
  const ipMulticastBlacklist = ref<IpMulticastBlacklistItem[]>();

  const ipMulticastWhiteTableData = computed(() => {
    return ipMulticastWhitelist.value?.map((item) => ({
      address: item.address,
      priority: item.priority,
      dataRate: item.dataRate,
      maxHopCount: item.maxHopCount,
    }));
  });

  const ipMulticastBlackTableData = computed(() => {
    return ipMulticastBlacklist.value?.map((item) => ({
      address: item.address,
    }));
  });

  const ipMulticastWhiteFormRef = ref<FormInst | null>(null);
  const ipMulticastWhiteFormValue = ref({
    address: '',
    priority: null,
    dataRate: null,
    maxHopCount: null,
  });
  const ipMulticastWhiteFormRules: FormRules = {
    address: [
      {
        required: true,
        validator(rule: FormItemRule, value: string) {
          if (!isMulticastIp(value)) {
            return new Error('不是合法的组播地址');
          }
          if (ipMulticastWhitelist.value?.map((item) => item.address).includes(value)) {
            return new Error('组播地址已存在');
          }
          return true;
        },
        trigger: ['input', 'blur'],
      },
    ],
    priority: [
      {
        required: true,
        validator: (rule: FormItemRule, value: number) => {
          if (value === null || value === undefined) {
            return new Error('不能为空');
          }
          return true;
        },
        trigger: ['input', 'blur'],
      },
    ],
    dataRate: [
      {
        required: true,
        validator: (rule: FormItemRule, value: number) => {
          if (value === null || value === undefined) {
            return new Error('不能为空');
          }
          return true;
        },
        trigger: ['input', 'blur'],
      },
    ],
    maxHopCount: [
      {
        required: true,
        validator: (rule: FormItemRule, value: number) => {
          if (value === null || value === undefined) {
            return new Error('不能为空');
          }
          return true;
        },
        trigger: ['input', 'blur'],
      },
    ],
  };

  const ipMulticastBlackFormRef = ref<FormInst | null>(null);
  const ipMulticastBlackFormValue = ref({
    address: '',
  });
  const ipMulticastBlackFormRules: FormRules = {
    address: [
      {
        required: true,
        validator(rule: FormItemRule, value: string) {
          if (!isMulticastIp(value)) {
            return new Error('不是合法的组播地址');
          }
          if (ipMulticastBlacklist.value?.map((item) => item.address).includes(value)) {
            return new Error('组播地址已存在');
          }
          return true;
        },
        trigger: ['input', 'blur'],
      },
    ],
  };

  const ipMulticastWhitelistColumns = [
    { title: 'ip地址', key: 'address' },
    { title: '优先级', key: 'priority' },
    { title: '数据速率', key: 'dataRate' },
    { title: '跳数', key: 'maxHopCount' },
    {
      title: '操作',
      key: 'actions',
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteIpMulticastWhite(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];

  const ipMulticastBlacklistColumns = [
    { title: 'ip地址', key: 'address' },
    {
      title: '操作',
      key: 'actions',
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteIpMulticastBlack(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];

  async function handleMulticastFilterSwitchChange(value: number) {
    await updateTransferConfig({ ipMulticastFilterMode: value });
  }

  async function handleIpMulticastWhiteSubmit(e: MouseEvent) {
    e.preventDefault();
    ipMulticastWhiteFormRef.value?.validate((errors) => {
      if (!errors) {
        // console.log('验证成功');
        const item: IpMulticastWhitelistItem = {
          address: ipMulticastWhiteFormValue.value.address,
          priority: ipMulticastWhiteFormValue.value.priority,
          dataRate: ipMulticastWhiteFormValue.value.dataRate,
          maxHopCount: ipMulticastWhiteFormValue.value.maxHopCount,
        };
        ipMulticastWhitelist.value?.push(item);
        updateTransferConfig({
          ipMulticastFilterMode: 0,
          ipMulticastWhitelist:
            ipMulticastWhitelist.value === undefined ? [] : [...ipMulticastWhitelist.value],
        })
          .then((result) => {
            if (result === 'OK') {
              message.success('组播ip数据白名单添加成功！');
            } else {
              message.error('组播ip数据白名单添加失败！');
            }
          })
          .catch((err) => {
            message.error('组播ip数据白名单添加失败！');
          });
      }
    });
  }

  async function handleIpMulticastBlackSubmit(e: MouseEvent) {
    e.preventDefault();
    ipMulticastBlackFormRef.value?.validate((errors) => {
      if (!errors) {
        // console.log('验证成功');
        const item: IpMulticastBlacklistItem = {
          address: ipMulticastBlackFormValue.value.address,
        };
        ipMulticastBlacklist.value?.push(item);
        updateTransferConfig({
          ipMulticastFilterMode: 1,
          ipMulticastBlacklist:
            ipMulticastBlacklist.value === undefined ? [] : [...ipMulticastBlacklist.value],
        })
          .then((result) => {
            if (result === 'OK') {
              message.success('组播ip数据黑名单添加成功！');
            } else {
              message.error('组播ip数据黑名单添加失败！');
            }
          })
          .catch((err) => {
            message.error('组播ip数据黑名单添加失败！');
          });
      }
    });
  }

  async function handleDeleteIpMulticastWhite(row: any, index: number) {
    ipMulticastWhitelist.value?.splice(index, 1);
    updateTransferConfig({
      ipMulticastFilterMode: 0,
      ipMulticastWhitelist:
        ipMulticastWhitelist.value === undefined ? [] : [...ipMulticastWhitelist.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('组播ip数据白名单删除成功！');
        } else {
          message.error('组播ip数据白名单删除失败！');
        }
      })
      .catch((err) => {
        message.error('组播ip数据白名单删除失败！');
      });
  }

  async function handleDeleteIpMulticastBlack(row: any, index: number) {
    ipMulticastBlacklist.value?.splice(index, 1);
    updateTransferConfig({
      ipMulticastFilterMode: 1,
      ipMulticastBlacklist:
        ipMulticastBlacklist.value === undefined ? [] : [...ipMulticastBlacklist.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('组播ip数据黑名单删除成功！');
        } else {
          message.error('组播ip数据黑名单删除失败！');
        }
      })
      .catch((err) => {
        message.error('组播ip数据黑名单删除失败！');
      });
  }
  /**********************************广播过滤*****************************************/
  const ipBroadcastFilterModeValue = ref<number>(0);
  const ipBroadcastWhitelist = ref<IpBroadcastWhitelistItem[]>();
  const ipBroadcastBlacklist = ref<IpBroadcastBlacklistItem[]>();

  const ipBroadcastWhiteTableData = computed(() => {
    return ipBroadcastWhitelist.value?.map((item) => ({
      port: item.port,
      priority: item.priority,
    }));
  });
  const ipBroadcastBlackTableData = computed(() => {
    return ipBroadcastBlacklist.value?.map((item) => ({ port: item.port }));
  });

  const addIpBroadcastWhitePortValue = ref<number | null>(null);
  const addIpBroadcastWhitePriorityValue = ref<number | null>(null);

  const addIpBroadcastBlackPortValue = ref<number | null>(null);

  const ipBroadcastWhitelistColumns = [
    { title: '端口', key: 'port' },
    { title: '优先级', key: 'priority' },
    {
      title: '操作',
      key: 'actions',
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteIpBroadcastWhitelist(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];

  const ipBroadcastBlacklistColumns = [
    { title: '端口', key: 'port' },
    {
      title: '操作',
      key: 'actions',
      render: (row: any, index: number) =>
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDeleteIpBroadcastBlacklist(row, index),
          },
          { default: () => '删除' }
        ),
    },
  ];

  async function handleSwitchChange(value: string) {
    // console.log(value);
    await updateTransferConfig({ ipBroadcastFilterMode: value });
  }

  async function handleDeleteIpBroadcastWhitelist(row: any, index: number) {
    ipBroadcastWhitelist.value?.splice(index, 1);
    updateTransferConfig({
      ipBroadcastWhitelist:
        ipBroadcastWhitelist.value === undefined ? [] : [...ipBroadcastWhitelist.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('广播ip数据(udp)白名单列表删除成功！');
        } else {
          message.error('广播ip数据(udp)白名单列表删除失败！');
        }
      })
      .catch((err) => {
        message.error('广播ip数据(udp)白名单列表删除失败！');
      });
  }

  async function handleAddIpBroadcastWhitelist() {
    if (
      addIpBroadcastWhitePortValue.value === null ||
      addIpBroadcastWhitePriorityValue.value === null
    ) {
      addIpBroadcastWhitePortValue.value = null;
      addIpBroadcastWhitePriorityValue.value = null;
      message.error('端口号或优先级不能为空');
      return;
    }

    if (
      ipBroadcastWhitelist.value
        ?.map((item) => item.port)
        .includes(addIpBroadcastWhitePortValue.value)
    ) {
      addIpBroadcastWhitePortValue.value = null;
      addIpBroadcastWhitePriorityValue.value = null;
      message.error('端口号已存在');
      return;
    }

    const item: IpBroadcastWhitelistItem = {
      port: addIpBroadcastWhitePortValue.value,
      priority: addIpBroadcastWhitePriorityValue.value,
    };
    ipBroadcastWhitelist.value?.push(item);

    updateTransferConfig({
      ipBroadcastWhitelist:
        ipBroadcastWhitelist.value === undefined ? [] : [...ipBroadcastWhitelist.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('广播ip数据(udp)白名单列表添加成功！');
        } else {
          message.error('广播ip数据(udp)白名单列表添加失败！');
        }
      })
      .catch((err) => {
        message.error('广播ip数据(udp)白名单列表添加失败！');
      });
  }

  async function handleDeleteIpBroadcastBlacklist(row: any, index: number) {
    ipBroadcastBlacklist.value?.splice(index, 1);
    updateTransferConfig({
      ipBroadcastFilterMode: 1,
      ipBroadcastBlacklist:
        ipBroadcastBlacklist.value === undefined ? [] : [...ipBroadcastBlacklist.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('广播ip数据(udp)黑名单列表删除成功！');
        } else {
          message.error('广播ip数据(udp)黑名单列表删除失败！');
        }
      })
      .catch((err) => {
        message.error('广播ip数据(udp)黑名单列表删除失败！');
      });
  }

  async function handleAddIpBroadcastBlacklist() {
    if (addIpBroadcastBlackPortValue.value === null) {
      addIpBroadcastBlackPortValue.value = null;
      message.error('端口号不能为空');
      return;
    }

    if (
      ipBroadcastBlacklist.value
        ?.map((item) => item.port)
        .includes(addIpBroadcastBlackPortValue.value)
    ) {
      addIpBroadcastBlackPortValue.value = null;
      message.error('端口号已存在');
      return;
    }

    const item: IpBroadcastBlacklistItem = {
      port: addIpBroadcastBlackPortValue.value,
    };
    ipBroadcastBlacklist.value?.push(item);

    updateTransferConfig({
      ipBroadcastFilterMode: 1,
      ipBroadcastBlacklist:
        ipBroadcastBlacklist.value === undefined ? [] : [...ipBroadcastBlacklist.value],
    })
      .then((result) => {
        if (result === 'OK') {
          message.success('广播ip数据(udp)黑名单列表添加成功！');
        } else {
          message.error('广播ip数据(udp)黑名单列表添加失败！');
        }
      })
      .catch((err) => {
        message.error('广播ip数据(udp)黑名单列表添加失败！');
      });
  }

  /**********************************实时信息*****************************************/
  interface RealInfo {
    ip: string;
    temp: string;
    noise: string;
    ant1Rssi: string;
    ant2Rssi: string;
    // ant1Snr: string;
    // ant2Snr: string;
    snr: string;
    distance: string;
  }

  // 定时器引用
  const refreshTimer = ref<number | null>(null);
  // 刷新间隔
  const refreshInterval = 5000; // 5秒刷新一次
  const isOpenRealInfo = ref<boolean>(false);

  const realInfoColumns = [
    { title: 'ip', key: 'ip' },
    { title: '芯片温度', key: 'temp' },
    { title: '底噪', key: 'noise' },
    { title: '天线1 Rssi', key: 'ant1Rssi' },
    { title: '天线2 Rssi', key: 'ant2Rssi' },
    // { title: '天线1 Snr', key: 'ant1Snr' },
    // { title: '天线2 Snr', key: 'ant2Snr' },
    { title: '信噪比 Snr', key: 'snr' },
    { title: '距离', key: 'distance' },
  ];

  const realInfoData = ref<RealInfo[]>([]);

  function handleTimer() {
    isOpenRealInfo.value = !isOpenRealInfo.value;
    if (isOpenRealInfo.value) {
      initRefreshTimer();
    } else {
      clearRefreshTimer();
    }
  }

  function getDistance(delay) {
    return ((delay * 10.0) / 1000000000.0) * 299792.458 * 1000.0; // 单位：米
  }

  async function updateRealInfo() {
    const statusSelf = await getStatusConfig();
    const noiseRssi = await getRssiStatus();
    const statusAdvanced = await getStatusAdvanced();
    const selfRealInfo: RealInfo = {
      ip: statusSelf.ip,
      temp: `${statusSelf.temp.toFixed(1)} ℃`,
      noise: `${noiseRssi.rssi[statusSelf.operatingFreq][0].toFixed(1)} dBm`,
      ant1Rssi: '',
      ant2Rssi: '',
      //   ant1Snr: '',
      //   ant2Snr: '',
      snr: `${statusAdvanced.aaSubband0Snr0Avg.toFixed(
        1
      )}[${statusAdvanced.aaSubband0Snr0Min.toFixed(1)},${statusAdvanced.aaSubband0Snr0Max.toFixed(
        1
      )}]`,
      distance: '',
    };

    realInfoData.value = [];
    const nodeinfos = [...statusSelf.nodeInfos];
    let j = 0;
    for (let i = 0; i < nodeinfos.length; ++i) {
      if (statusSelf.selfId === nodeinfos[i].id) {
        realInfoData.value.push(selfRealInfo);
        continue;
      }
      const otherIp = nodeinfos[i].ip;
      const otherStatus = await getStatusByIp(otherIp);
      const otherNoiseRssi = await getRssiStatusByIp(otherIp);
      const otherStatusAdvanced = await getStatusAdvancedByIp(otherIp);
      const otherRealInfo: RealInfo = {
        ip: otherIp,
        temp: `${otherStatus.temp.toFixed(1)} ℃`,
        noise: `${otherNoiseRssi.rssi[otherStatus.operatingFreq][0].toFixed(1)} dBm`,
        ant1Rssi: `${otherStatus.nodesRssi[j].ant1Rssi.toFixed(1)} dBm`,
        ant2Rssi: `${otherStatus.nodesRssi[j].ant2Rssi.toFixed(1)} dBm`,
        // ant1Snr: '',
        // ant2Snr: '',
        snr: `${otherStatusAdvanced.aaSubband0Snr0Avg.toFixed(
          1
        )}[${otherStatusAdvanced.aaSubband0Snr0Min.toFixed(
          1
        )},${otherStatusAdvanced.aaSubband0Snr0Max.toFixed(1)}]`,
        distance: `${getDistance(otherStatus.transmissionDelay[j].delay).toFixed(1)} 米`,
      };
      realInfoData.value.push(otherRealInfo);
      j++;
    }
  }

  // 初始化定时器
  function initRefreshTimer() {
    updateRealInfo();
    refreshTimer.value = window.setInterval(() => {
      //   console.log('111');
      updateRealInfo();
    }, refreshInterval);
  }
  // 清除定时器
  function clearRefreshTimer() {
    realInfoData.value = [];
    if (refreshTimer.value) {
      clearInterval(refreshTimer.value);
      refreshTimer.value = null;
    }
  }

  onMounted(async () => {
    try {
      const rfconfig = await getRfConfig();
      Object.assign(rfFormValue.value, {
        dataEncryptionMode: rfconfig.dataEncryptionMode,
        dataEncryptionKey: rfconfig.dataEncryptionKey,
        meshName: rfconfig.meshName,
        freqMode: rfconfig.freqMode,
        span: rfconfig.span,
        freqList: [...rfconfig.freqList],
        forbiddenFreqBands: [...rfconfig.forbiddenFreqBands],
        freqDefault: rfconfig.freqDefault,
        pwAtten1: rfconfig.pwAtten1,
        pwAtten2: rfconfig.pwAtten2,
        rfDisable: rfconfig.rfDisable,
      });

      Object.assign(transferFormValue.value, {
        dataTransferMode: rfconfig.dataTransferMode,
        linkSnrThreshold: rfconfig.linkSnrThreshold,
        maxMcformat: rfconfig.maxMcformat,
        minTF: rfconfig.minTF,
      });

      multicastIncomingWhiteList.value = [...rfconfig.ipMulticastIncomingWhitelist];
      multicastIncomingBlackList.value = [...rfconfig.ipMulticastIncomingBlacklist];

      ipBroadcastFilterModeValue.value = rfconfig.ipBroadcastFilterMode;

      ipBroadcastWhitelist.value = [...rfconfig.ipBroadcastWhitelist];
      ipBroadcastBlacklist.value = [...rfconfig.ipBroadcastBlacklist];

      ipMulticastFilterModeValue.value = rfconfig.ipMulticastFilterMode;

      ipMulticastWhitelist.value = [...rfconfig.ipMulticastWhitelist];
      ipMulticastBlacklist.value = [...rfconfig.ipMulticastBlacklist];
    } catch (error) {
      message.error('获取射频信息失败！');
    }
  });

  onBeforeUnmount(() => {
    clearRefreshTimer();
  });
</script>
